<?php
namespace app\admin\model;

use app\admin\controller\Resources;
use app\common\model\Upload;
use app\model\CommonModel;
use app\model\RsRelate;
use think\facade\Db;

class RsBrand extends CommonModel
{


    /* 商品分类 */
    public function cate()
    {
        return $this->belongsTo(RsCate::class, 'cate_id');
    }

    public function brandList($params)
    {
        $where = $this->setWhere($params);
        $paginate = [
            'page' => $params['page'] ?? 1,
            'list_rows' => $params['list_rows'] ?? 10,
        ];
        $list = self::where($where)
            ->with('cate')
            ->order('id desc')
            ->paginate($paginate)
            ->toArray();
        if ($list['data']) {
            $brandIds = array_unique(array_column($list['data'], 'id'));
            $brandCate = Db::name('rs_relate')
                ->field('cate_id, brand_id')
                ->whereIn('brand_id', $brandIds)
                ->where('status', 1)
                ->select()
                ->toArray();
            $cateIds = array_column($brandCate, 'cate_id');
            $cate = Db::name('rs_cate')
                ->whereIn('id', $cateIds)
                ->whereNull('deleted_at')
                // ->where('status', 1)
                ->column('cate_name', 'id');
            $brandList = [];
            foreach ($brandCate as $v) {
                if (!empty($cate[$v['cate_id']])) {
                    $brandList[$v['brand_id']][] = $cate[$v['cate_id']];
                }
            }

            foreach ($list['data'] as $k => $v) {
                if (!empty($brandList[$v['id']])) {
                    $list['data'][$k]['cate_name'] = implode('/', $brandList[$v['id']]);
                } else {
                    $list['data'][$k]['cate_name'] = '';
                }
            }
        }
        
        return success('操作成功', $list);
    }

    //设置条件
    public function setWhere($params)
    {
        $where = [];
        if (isset($params['key']) && !empty($params['key'])) {
            $where[]=['brand_name|id','like','%'.$params['key'].'%'];
        }
        if (isset($params['status']) && $params['status'] != -1) {
            $where[]=['status','=',$params['status']];
        }
        return $where;
    }
    /**
     *    选择品牌
     */
    public function brandSelect()
    {
        $data=self::where("status", 1)->column("brand_name", "id");
        return success('操作成功', $data);
    }
    /**
     *  新增修改分类
     */
    public function optionBrand($params)
    {
        $info = self::where("id", $params['id'])->find();
        if (empty($info)) {
            $info = new self();
        }
        if (!empty($params['brand_name'])) {
            $info->brand_name = $params['brand_name'];
        }
        $info->status = $params['status'];
        $info->brand_img = $params['brand_img'];
        $info->save();
        return success('保存成功！');
    }
    /**
     *  修改状态
     */
    public function optionStatus($params)
    {
        $info=self::where("id", $params['id'])->find();
        if (empty($params['id'])) {
            return fail('该品牌不存在');
        }
        $info->status=$params['status'];
        $info->save();
        return success('保存成功！');
    }

    /**
     * 上传品牌图标
     */
    public function uploadBrand()
    {
        try {
            $file = request()->file('file');
            $file_types = explode('.', $_FILES['file']['name']);
            $file_type = $file_types[count($file_types) - 1]; //后缀
            $attr = ['png','jpg','jpeg','pjpeg','x-png','png'];
            $file_type=strtolower($file_type);
            if (!in_array($file_type, $attr)) {
                return fail('格式错误，请上传正确的图片文件格式！');
            }
            $maxSize = 4194304;
            if ($_FILES["file"]["size"] > $maxSize) {
                return fail('文件大小不能超过4M！');
            }
            $brandImg = '';
            $params = [
                'dirName' => 'brand',
                'file'    => $file,
            ];
            $result = (new Upload())->image($params);
            $result = json_decode($result->getContent(),true);
            if ($result['data']) {
                $brandImg = $result['data']['url'];
            }
            if (empty($brandImg)) {
                return fail('上传失败');
            }
            // 上传到本地服务器
//            $savePath = date('Ymd').'/'.md5((string) microtime(true)).'/'.$file->getOriginalName();
//            $savename = \think\facade\Filesystem::disk('public')->putFileAs('brand', $file, $savePath);
//            $savename = str_replace('\\', '/', $savename);
//            $brandImg = request()->domain() . '/storage/' . $savename;
        } catch (\Exception $e) {
            return fail('上传失败：'.$e->getMessage());
        }
        return success('上传成功', [
            'url' =>$brandImg,
        ]);
    }

    /**
     * 导入品牌
     */
    public static function importBrand($brandName, $cateId, $info="")
    {
        $info=str_replace(' ', '\n', $info);
        $info=array_filter(explode('\n', $info));
        $info=implode('\n', $info);
        $brand=self::where("brand_name", $brandName)->find();
        if (empty($brand)) {
            $brand=new self();
            $brand->brand_name=$brandName;
        }
        $brand->brand_info=$info;
        $brand->save();
        //保存关联
//        $relate=RsRelate::where("cate_id",$cateId)->where("brand_id",$brand->id)->find();
//        if(empty($relate)){
//            $relate=new RsRelate();
//            $relate->cate_id=$cateId;
//            $relate->brand_id=$brand->id;
//            $relate->save();
//        }
        return $brand->id;
    }
}
